from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from .serializers import ScheduleRequestSerializer, ScheduleResultSerializer
from .algorithm import run_scheduling_algorithm

class ScheduleAPIView(APIView):
    """
    调度API接口：接收分段和胎位参数，调用算法，返回调度结果。
    仅支持POST请求。
    """
    def post(self, request):
        # 1. 校验前端传来的参数
        serializer = ScheduleRequestSerializer(data=request.data)
        if serializer.is_valid():
            segments = serializer.validated_data['segments']
            mold_positions = serializer.validated_data['mold_positions']
            rule = serializer.validated_data.get('rule', None)
            # 2. 调用算法，获取调度结果
            result = run_scheduling_algorithm(segments, mold_positions, rule)
            # 3. 用结果序列化器格式化输出
            result_serializer = ScheduleResultSerializer(result, many=True)
            return Response({'results': result_serializer.data}, status=status.HTTP_200_OK)
        else:
            # 参数校验失败，返回400和错误信息
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def get(self, request):
        # 友好提示：只支持POST
        return Response({"detail": "请使用POST方法提交调度参数"}, status=405) 